//
//  SSSearchViewController.m
//  starspaceVR
//
//  Created by 曹端芹 on 17/9/12.
//  Copyright © 2017年 starspace. All rights reserved.
//

#import "SSSearchViewController.h"

#import "SSSearchResultViewController.h"

#define kMargin 10
#define TagMaxCol 3

#define SEARCH_HISTORY_CACHE_PATH [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"SearchHistories.plist"]


@interface SSSearchViewController ()<UISearchBarDelegate>
@property (nonatomic,weak) UISearchBar *searchBar;
@property (nonatomic,weak) UIView *hotSearchView;
@property (nonatomic,weak) UIView *searchHistoryView;
@property (nonatomic,weak) UIView *searchHistoryContentView;
@property (nonatomic,strong) UIButton *emptyButton;

@property (nonatomic,strong) NSMutableArray *searchHistories;
@end

@implementation SSSearchViewController

- (NSMutableArray *)searchHistories {
    if (!_searchHistories) {
        _searchHistories = [NSMutableArray arrayWithArray:[NSKeyedUnarchiver unarchiveObjectWithFile:SEARCH_HISTORY_CACHE_PATH]];
    }
    return _searchHistories;
}

- (UIButton *)emptyButton {
    if (!_emptyButton) {
        _emptyButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _emptyButton.titleLabel.font = kFont(12);
        [_emptyButton setTitle:@"清空" forState:UIControlStateNormal];
        [_emptyButton setTitleColor:kRGBColor(113, 113, 113) forState:UIControlStateNormal];
        [_emptyButton addTarget:self action:@selector(emptySearchHistoryDidClick) forControlEvents:UIControlEventTouchUpInside];
        [_emptyButton setImage:[UIImage imageNamed:@"empty"] forState:UIControlStateNormal];
    }
    return _emptyButton;
}



- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.title = @"搜索";
    [self setupSearchBar];
    [self setupHotSearchContenView];
    [self setupSearchHistoryContentView];
    
    [self requestHotSearchWords];
    
}

- (void) setupSearchBar {
    UISearchBar *searchBar  = [[UISearchBar alloc] init];
    searchBar.frame = CGRectMake(kMargin, 1.5 * kMargin, kScreenWidth - 2 *kMargin, 30);
    searchBar.backgroundImage = [UIImage imageNamed:@"clearImage"];
    searchBar.delegate = self;
    searchBar.backgroundColor = kRGBColor(249, 249, 249);
    searchBar.placeholder = @"请输入搜索关键词";
    [self.view addSubview:searchBar];
    self.searchBar = searchBar;


}

- (void) setupHotSearchContenView {
    
    UIView *contentView = [[UIView alloc] init];
    contentView.frame = CGRectMake(0, 60, kScreenWidth, 40);
    [self.view addSubview:contentView];
    
    UILabel *hotL = [self setupTitleLabel:@"热门搜索"];
    hotL.frame = CGRectMake(kMargin, 0, kScreenWidth - 2 *kMargin, 30);
    [contentView addSubview:hotL];
    
    UIView *lineView = [[UIView alloc] init];
    lineView.frame = CGRectMake(kMargin, CGRectGetMaxY(hotL.frame), kScreenWidth - 2 *kMargin, 1);
    lineView.backgroundColor = kRGBColor(113, 113, 113);;
    [contentView addSubview:lineView];
    
    UIView *hotSearchView = [[UIView alloc] init];
    hotSearchView.frame = CGRectMake(kMargin, 40, kScreenWidth - 2 * kMargin, 40);
    self.hotSearchView = hotSearchView;
    [contentView addSubview:hotSearchView];

}

- (void) setupSearchHistoryContentView {
    
    UIView *contentView = [[UIView alloc] init];
    contentView.frame = CGRectMake(0, 140, kScreenWidth, 40);
    [self.view addSubview:contentView];
    UILabel *hisL = [self setupTitleLabel:@"搜索历史"];
    hisL.frame = CGRectMake(kMargin, 5, kScreenWidth - 2 * kMargin, 30);
    [contentView addSubview:hisL];
    
    self.emptyButton.frame = CGRectMake(kScreenWidth - 70, 5, 60, 30);
    [contentView addSubview:self.emptyButton];
    
    self.searchHistoryContentView = contentView;
    
    UIView *searchHistoryView = [[UIView alloc] init];
    searchHistoryView.frame = CGRectMake(kMargin, 40, kScreenWidth - 2 * kMargin, 40);
    self.searchHistoryView = searchHistoryView;
    [contentView addSubview:searchHistoryView];
    
    [self addAndLayoutTagsWithTagsContentView:self.searchHistoryView tagTexts:self.searchHistories];


}


- (void)requestHotSearchWords {
    
    [self showHUD];
    [SSNetworkManager getWithURLString:kSSHotwordsAPI parameters:nil success:^(NSDictionary *responseDict) {
        [self dismissHUD];
        NSArray *hotSaearches = responseDict[@"data"];
        [self addAndLayoutTagsWithTagsContentView:self.hotSearchView tagTexts:hotSaearches];
       
    } failure:^(NSError *error) {
        [self dismissHUD];
    }];
    
}



- (void)addAndLayoutTagsWithTagsContentView:(UIView *)contentView tagTexts:(NSArray<NSString *> *)tagTexts {
    
    if (self.searchHistories.count == 0) {
        self.searchHistoryContentView.hidden = YES;
    }else{
        self.searchHistoryContentView.hidden = NO;
    }
    
    [contentView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    for (int i = 0; i < tagTexts.count; i ++) {
        UILabel *label = [self labelWithTitle:tagTexts[i]];
        if (contentView == self.hotSearchView) {
            label.backgroundColor = [UIColor randomColor];
            label.textColor = [UIColor whiteColor];
        }
        
        [label addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tagDidClick:)]];
        [contentView addSubview:label];
    }
    
    CGFloat currentX = 0;
    CGFloat currentY = 0;
    CGFloat countRow = 0;
    CGFloat countCol = 0;
    
    for (int i = 0; i < contentView.subviews.count; i ++) {
        
        UILabel *subView = contentView.subviews[i];
        if (subView.width > contentView.width) {
            subView.width = contentView.width;
        }
        if (currentX + subView.width + kMargin * countRow > contentView.width) {
            subView.x = 0;
            subView.y = (currentY += subView.height) + kMargin * ++countCol;
            currentX = subView.width;
            countRow = 1;
        }else{
            subView.x = (currentX += subView.width) - subView.width + kMargin * countRow;
            subView.y = currentY + kMargin * countCol;
            countRow ++;
            
        }
    }
    
    
    contentView.height = CGRectGetMaxY(contentView.subviews.lastObject.frame);
    contentView.superview.height = CGRectGetMaxY(contentView.frame);
    if (contentView == self.hotSearchView) {
        self.searchHistoryContentView.y = CGRectGetMaxY(contentView.superview.frame) + kMargin;
    }
}

- (void)tagDidClick:(UITapGestureRecognizer *)tap {
    
    [self.searchBar resignFirstResponder];
    UILabel *label = (UILabel *)tap.view;
    self.searchBar.text = label.text;
    SSSearchResultViewController *resultViewController = [[SSSearchResultViewController alloc] init];
    resultViewController.word = label.text;
    [self.navigationController pushViewController:resultViewController animated:YES];
    
    [self.searchHistories removeObject:label.text];
    [self.searchHistories insertObject:label.text atIndex:0];
    [NSKeyedArchiver archiveRootObject:self.searchHistories toFile:SEARCH_HISTORY_CACHE_PATH];
    [self addAndLayoutTagsWithTagsContentView:self.searchHistoryView tagTexts:self.searchHistories];
    
}


- (void)emptySearchHistoryDidClick {
    [self.searchBar resignFirstResponder];
    [self.searchHistories removeAllObjects];
    [NSKeyedArchiver archiveRootObject:self.searchHistories toFile:SEARCH_HISTORY_CACHE_PATH];
    self.searchHistoryContentView.hidden = YES;
   
}

#pragma mark - UISearchBarDelegate
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {

    NSString *searchText = [searchBar.text stringByReplacingOccurrencesOfString:@" " withString:@""];
    [self.searchHistories removeObject:searchText];
    [self.searchHistories insertObject:searchText atIndex:0];
    [NSKeyedArchiver archiveRootObject:self.searchHistories toFile:SEARCH_HISTORY_CACHE_PATH];
    [searchBar resignFirstResponder];
    [self addAndLayoutTagsWithTagsContentView:self.searchHistoryView tagTexts:self.searchHistories];
    SSSearchResultViewController *resultViewController = [[SSSearchResultViewController alloc] init];
    resultViewController.word = searchBar.text;
    [self.navigationController pushViewController:resultViewController animated:YES];
    searchBar.text = @"";
    
}


- (UILabel *)labelWithTitle:(NSString *)title {
    UILabel *label = [[UILabel alloc] init];
    label.userInteractionEnabled = YES;
    label.font = [UIFont systemFontOfSize:12];
    label.text = title;
    label.textColor = [UIColor grayColor];
    label.backgroundColor = kRGBColor(249, 249, 249);
    label.layer.cornerRadius = 3;
    label.clipsToBounds = YES;
    label.textAlignment = NSTextAlignmentCenter;
    [label sizeToFit];
    label.width += 14;
    label.height += 10;
    return label;
}

- (UILabel *)setupTitleLabel:(NSString *)title {
    UILabel *titleLabel = [[UILabel alloc] init];
    titleLabel.text = title;
    titleLabel.font = kFont(13);
    titleLabel.tag = 1;
    titleLabel.textColor = kRGBColor(113, 113, 113);
    [titleLabel sizeToFit];
    titleLabel.x = 0;
    titleLabel.y = 0;
    return titleLabel;
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.searchBar resignFirstResponder];
}





- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
